package com.kuang.login.dao;

import com.kuang.login.model.User;
import com.kuang.login.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by 郭浩 on 2020/9/25 20:15
 */
public class userMysqlDao implements userDao{
    @Override
    public int register(User user) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        try {
            queryRunner.update("insert into mvc values (null,?,?,?)",
                    user.getUsername(),
                    user.getPassword(),
                    user.getGender());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 404;
        }
        return 200;
    }

    @Override
    public int login(User user) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        Long query = null;
        try {
            query = (Long) queryRunner.query("select count(id) from t_user where username = ? and password = ?", new ScalarHandler(),
                    user.getUsername(),
                    user.getPassword());
            if (query == 1){
                return 200;
            }
            return 404;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 500;
        }
    }

    @Override
    public int getUserCount() {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        Long query = null;
        try {
            query = (Long) queryRunner.query("select count(id) from t_user", new ScalarHandler());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return query.intValue();
    }

    @Override
    public List<User> queryCurrentPageUser(int curPage, int pageSize) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        List<User> users = null;

        try {
            users = queryRunner.query("select * from t_user limit ? offset ?", new BeanListHandler<User>(User.class),
                    pageSize,
                    (curPage - 1) * pageSize);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return users;
    }
}
